﻿using System;
using System.Linq;
using GiteeApi.Dtos;
using GiteeApi.Models;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using GiteeApi.Utils;

namespace GiteeApi.Services
{
    public class UserServices
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        private readonly giteeapiContext _giteeapiContext;

        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="giteeapiContext"></param>
        public UserServices(giteeapiContext giteeapiContext)
        {
            _giteeapiContext = giteeapiContext;
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="loginDto">邮箱；密码</param>
        /// <returns>登陆结果</returns>
        public async Task<UserInfo> LoginAsync(LoginDto loginDto)
        {
            return await _giteeapiContext.UserInfos
                .FirstOrDefaultAsync(x => x.Email == loginDto.Email &&
                                          x.Password == loginDto.Password);
        }

        /// <summary>
        /// 通过邮箱检查是否被注册
        /// </summary>
        /// <param name="Email">邮箱</param>
        /// <returns>是否被注册</returns>
        public async Task<bool> CheckEmailExistAsync(string Email)
        {
            return await _giteeapiContext.UserInfos.FirstOrDefaultAsync(x => x.Email == Email) is not null;
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="registerDto">邮箱验证码；邮箱；密码；确认密码</param>
        /// <returns>注册结果</returns>
        public async Task<bool> RegisterAsync(RegisterDto registerDto)
        {
            // 创建注册对象
            var userInfo = new UserInfo
            {
                Email = registerDto.Email,
                Password = registerDto.Password,
                Time = DateTime.Now,
                Delete = 0
            };

            await _giteeapiContext.UserInfos.AddAsync(userInfo);
            return await _giteeapiContext.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="password">密码</param>
        /// <returns>修改结果</returns>
        public async Task<bool> ChangePwdAsync(int userId, string password)
        {
            var userInfo = await _giteeapiContext.UserInfos.FirstOrDefaultAsync(a => a.Id == userId);
            userInfo.Password = MD5Util.Get(password);
            return await _giteeapiContext.SaveChangesAsync() > 0;
        }
    }
}
